package org.apiframe.handler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.log.StaticLog;
import com.alibaba.fastjson.JSONObject;
import org.apiframe.utils.ClassLoaderUtils;
import org.apiframe.utils.ExceptionEnum;
import org.apiframe.utils.HttpUtils;
import io.vertx.core.http.HttpServerRequest;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ApiHandler {

    public static String invoke(HttpServerRequest request)  {
        String paramsClass = request.getParam("class");
        String paramsMethod = request.getParam("method");
        String retsult ="";
        //封装所有的请求参数
        JSONObject requestJSONParams = HttpUtils.getRequest(request);
        try {
        if(StrUtil.isBlank(paramsClass) || StrUtil.isBlank(paramsMethod)){
            return "参数有误";
        }

        ClassLoader loader = ClassLoaderUtils.getInstance();
        Class<?> c = loader.loadClass(paramsClass);
        //获取方法
        Method method = c.getMethod(paramsMethod,String.class);
        //调用
        retsult = (String) method.invoke(c.newInstance(),requestJSONParams.toString());
        } catch (InvocationTargetException e) {
            retsult = ExceptionEnum.方法执行异常.name();
            StaticLog.error(e,"执行"+paramsClass+"."+paramsMethod+"方法异常,参数:"+requestJSONParams.toString());
        } catch (NoSuchMethodException e) {
            retsult= ExceptionEnum.方法不存在.name()+e.getMessage();
            StaticLog.error(e);
        } catch (IllegalAccessException e) {
            StaticLog.error(e);
        } catch (InstantiationException e) {
            StaticLog.error(e);
        } catch (ClassNotFoundException e) {
            retsult= ExceptionEnum.类不存在.name()+e.getMessage();
            StaticLog.error(e);
        }
        return retsult;
    }
}
